package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.DishMapper;
import com.sky.result.PageResult;
import com.sky.service.DishFlavorService;
import com.sky.service.DishService;
import com.sky.service.SetmealDishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import static org.apache.commons.lang3.ObjectUtils.min;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    public Long countByCategoryId(Long categoryId) {
        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, categoryId);
        return dishMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public Dish queryById(Long id) {
        return dishMapper.selectById(id);
    }

    @Override
    public DishVO queryByIdWithFlavor(Long id) {
        // 查询菜品
        Dish dish = dishMapper.selectById(id);

        // 查询菜品口味
        List<DishFlavor> flavors = dishFlavorService.queryByDishId(id);

        // 创建返回对象
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setFlavors(flavors);

        return dishVO;
    }

    @Override
    public List<Dish> listByCategoryId(Long categoryId) {

        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<Dish>()
                .eq(Dish::getCategoryId, categoryId)
                .eq(Dish::getStatus, StatusConstant.ENABLE);

        return dishMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public List<DishVO> listByCategoryIdWithFlavor(Long categoryId) {

        List<Dish> dishList = listByCategoryId(categoryId);
        List<DishVO> dishVOList = new ArrayList<>();

        for (Dish dish : dishList) {
            Long dishId = dish.getId();
            DishVO dishVO = queryByIdWithFlavor(dishId);
            dishVOList.add(dishVO);
        }

        return dishVOList;
    }


    @Override
//    @AutoFill(value = OperationType.UPDATE)
    public Dish startOrStop(Long id, Integer status) {
        Dish dish = dishMapper.selectById(id);
        if (dish == null) {
            return null;
        }
        dish.setStatus(status);
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        dishMapper.updateById(dish);
        return dish;
    }


    @Override
    public PageResult pageQuery(DishPageQueryDTO dishPageQueryDTO) {


        int pageNum = dishPageQueryDTO.getPage();
        int pageSize = dishPageQueryDTO.getPageSize();

        String name = dishPageQueryDTO.getName();
        Integer categoryId = dishPageQueryDTO.getCategoryId();
        Integer status = dishPageQueryDTO.getStatus();

        // 构造分页条件
        Page<Dish> page = Page.of(pageNum, pageSize);

        // 构造查询条件
        lambdaQuery()
                .like(name != null, Dish::getName, name)
                .eq(categoryId != null, Dish::getCategoryId, categoryId)
                .eq(status != null, Dish::getStatus, status)
                .page(page);

        PageResult pageResult = new PageResult();

        // 设置属性
        // TODO 分页查询失败，需要修改
        pageResult.setTotal(page.getRecords().size());

        int l = (pageNum - 1) * pageSize;
        // 左端起点超出起点
        if (l >= page.getRecords().size()) {
            return pageResult;
        }

        // 右端 = 左端 +
        int r = l + pageSize;
        r = min(r, page.getRecords().size());
        pageResult.setRecords(page.getRecords().subList(l, r));

        return pageResult;
    }

    @Override
    @Transactional
    public void deleteByIds(List<Long> idList) {

        // 依次处理
        for (Long dishId : idList) {
            // 查询对应菜品
            Dish dish = dishMapper.selectById(dishId);

            // 判断菜品是否在售
            if (Objects.equals(dish.getStatus(), StatusConstant.ENABLE)) {
                // 菜品在售，不可删除
                throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
            }

            // 判断菜品是否被套餐关联
            if (setmealDishService.countByDishId(dishId) != 0) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            // 删除菜品
            dishMapper.deleteById(dish);

            // 删除菜品对应口味
            dishFlavorService.deleteByDishId(dishId);
        }

    }

    @Override
    @Transactional
    public Dish create(DishDTO dishDTO) {

        // 操作菜品表
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dish.setCreateTime(LocalDateTime.now());
        dish.setCreateUser(BaseContext.getCurrentId());
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        // 菜品表插入数据
        dishMapper.insert(dish);

        dish = dishMapper.selectOne(
                new LambdaQueryWrapper<Dish>()
                        .eq(Dish::getName, dish.getName())
        );

        Long dishId = dish.getId();

        // 操作口味表
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (dishFlavorList != null && !dishFlavorList.isEmpty()) {

            // 遍历赋值 dishId
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });

            dishFlavorService.createBatch(dishFlavorList);
        }


        return dish;
    }

    @Override
    public DishVO updateByIdWithFlavor(DishDTO dishDTO) {
        // 修改基本信息
        Long dishId = dishDTO.getId();
        // 查询原数据
        Dish dish = dishMapper.selectById(dishId);
        // 拷贝属性
        BeanUtils.copyProperties(dishDTO, dish);
        // 更新时间
        dish.setUpdateTime(LocalDateTime.now());
        dish.setUpdateUser(BaseContext.getCurrentId());
        // 更新菜品表
        dishMapper.updateById(dish);

        // 修改口味信息
        // 删除原有口味
        dishFlavorService.deleteByDishId(dishId);
        // 更新菜品口味
        List<DishFlavor> dishFlavorList = dishDTO.getFlavors();
        if (dishFlavorList != null && !dishFlavorList.isEmpty()) {
            // 遍历赋值 dishId
            dishFlavorList.forEach(dishFlavor -> {
                dishFlavor.setDishId(dishId);
            });
            dishFlavorService.createBatch(dishFlavorList);
        }

        return null;
    }


}
